import {useGetSiteSettingsQuery, usePortalQuery} from "@/generated/graphql";
import i18n from "@/locales";
import {defaultsDeep, isNull, keys, pick, pickBy} from "lodash-es";
import {computed, ComputedRef} from "vue";
import {ReturnSiteSetting, SiteContent, siteSettings,} from "./defaultSiteSetting";
import {useUserStore} from "@/stores/auth";

export const useSiteSetting = () => {
    const userStore = useUserStore();
    const userPortal = userStore.user?.portal;
    const lang = computed(() => i18n.global.locale as SiteContent);
    //TODO 查询siteSetting和查询portal 逻辑
    const portalResult = usePortalQuery({
        variables: {
            where: {
                id: userPortal,
            },
        },
    });
    const siteSettingResult = useGetSiteSettingsQuery({
        variables: {
            first: 1,
        },
    });

    const siteSetting: ComputedRef<ReturnSiteSetting> = computed(() => {
        const site = siteSettingResult.data.value?.siteSettings[0] ?? {};
        const result = defaultsDeep(
            pickBy(portalResult.data.value?.portal?.extends, (a) => !isNull(a)),
            pickBy(site, (a) => !isNull(a)),
            pickBy(siteSettings, (a) => !isNull(a))
        );
        const r = pick(result, keys(siteSettings)) as ReturnSiteSetting;
        return r;
    });
    return {siteSetting, lang};
};
